package cn.itcast.mq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;

@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {
    /*@Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }*/


    /* 生产者消息确认（生产者回执）配置开启publish-return功能，基于callback机制
    每个RabbitTemplate只能配置一个ReturnCallback，所以在项目加载时配置*/
    /**
     * public interface ReturnCallback {
     * void returnedMessage(Message message, int replyCode,
     * String replyText, String exchange, String routingKey);
     * }
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取RabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 设置ReturnCallback
        rabbitTemplate.setReturnCallback(new ReturnCallback() {
             @Override
             public void returnedMessage(Message message, int replyCode,
                                         String replyText, String exchange,
                                         String routingKey) {
                 // 投递消息
                 log.info("消息发送失败，应答码{}，原因{}，交换机{}，路由键{}，消息{}",
                         replyCode, replyText, exchange, routingKey, message.toString());
                 // 若有业务需要，可以重发消息
                 // .......
             }
         });
    }




}
